const connection = require("../app/database");

const sqlFragment = `
  SELECT
    m.id id, m.content content, m.createAt createTime, m.updateAt updateTime,
    JSON_OBJECT('id', u.id, 'name', u.name) author,
    (SELECT COUNT(*) FROM comment c WHERE c.moment_id = m.id) commentCount
  FROM moments m
  LEFT JOIN users u ON m.user_id = u.id
`

class MomentService {
  async create(userId, content) {
    const statement = `INSERT INTO moments (content, user_id) VALUES(?, ?);`;

    const [result] = await connection.execute(statement, [content, userId]);

    return result;
  }

  async getMomentById(momentId) {
    const statement = `${sqlFragment}
                       WHERE m.id = ?;`;

    const [result] = await connection.execute(statement, [momentId]);

    return result;
  }

  async getMomentList(offset, size) {
    const statement = `${sqlFragment}
                       LIMIT ?, ?;`

    const [result] = await connection.execute(statement, [offset, size]);

    return result;
  }

  async updateMoment(content, momentId) {
    const statement = `UPDATE moments SET content = ? WHERE id = ?;`

    const [result] = await connection.execute(statement, [content, momentId])

    return result
  }

  async deleteMoment(momentId) {
    const statement = `DELETE FROM moments WHERE id = ?;`

    const [result] = await connection.execute(statement, [momentId])

    return result
  }
}

module.exports = new MomentService();
